package gptma.fo.filter;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// @WebFilter(urlPatterns="/pages/*")
public class SessionLossFilter implements Filter {

	private static final String LOGIN_PAGE = "login.jsf";

	@Override
	public void doFilter(ServletRequest requ, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) requ;
		HttpServletResponse res = (HttpServletResponse) resp;

		HttpSession session = req.getSession(false);
		Principal p = req.getUserPrincipal();

		if (session == null) {
			req.setAttribute("sessionLost", true);
		}

		if (session == null || p == null) {
			res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
		}

		chain.doFilter(req, res);
	}

	@Override
	@SuppressWarnings("unused")
	public void init(FilterConfig conf) {
		// no-op
	}

	@Override
	public void destroy() {
		// no-op
	}
}
